import Plugin from './plugin'
import {CN,EN,UI,Cst} from '../config'

const cssText = `
.#{icn.progress} {
	position:relative;
    background-color: #fff;
    width:100%;
    height:100%;
}
.#{icn.progress} canvas{
	top:50%;
	left:0;
	transform:translate3d(0,-50%,0);
	cursor:pointer;
	background-color: #{icn.btnBg};
}
.#{icn.btn}{
	width: 15px;
    height: 15px;
    background-color: #{icn.black};
    z-index: 1;
    position: absolute;
    border-radius: 50%;
    border: none;
    outline: none;
    left: 0;
    top: 50%;
    transform: translate3d(0,-50%,0);
    cursor: pointer;
}
`
export default class ProgressBar extends Plugin{
	constructor(...args){
		super(...args)
		this.name="ProgressBar"
		this.mpx = false
		this.createClassName({
			progress:"progress",
			btn:"progress-btn"
		})
		this.injectStyle(cssText,this.cn)
		this.render()
		this.bind()
	}
	bind(){
		this.on(Cst.focusIn,this.onFocusIn.bind(this))
		this.$dom.addEventListener(EN.down,this.onMousedown.bind(this))
		document.addEventListener(EN.up,this.onMouseup.bind(this))
		document.addEventListener(EN.move,this.onMousemove.bind(this))
		this.cvs.addEventListener(EN.click,this.onClick.bind(this))
	}
	render(){
		let cn = this.cn
		this.$dom = document.createDOM("div",{
			class:cn.progress
		})
		this.$dom.innerHTML = `
			<canvas class="${CN.abs}"></canvas>
			<button class="${cn.btn}">
		`
		this.cvs = this.$dom.query("canvas")
		this.btn = this.$dom.query("button")
		this.ctx = this.cvs.getContext("2d")
	}
	onMousedown(e){
		e.stopPropagation()
		let target = e.target
		this.mpx = false
		if(target!==this.btn)return
		this.mpx = e.pageX-target.offsetLeft
	}
	onMousemove(e){
		if(!this.active)return
		e.stopPropagation()
		if(this.mpx===false)return
		let dx = e.pageX-this.mpx
		this.onEmit(dx)
	}
	onMouseup(e){
		if(!this.active)return
		e.stopPropagation()
		if(this.mpx===false)return
		this.mpx=false
	}
	onEmit(dx){
		let max = this.cacheData.max
		let width = this.rect.width
		dx = dx>=width?width:dx
		dx = dx<0?0:dx
		this.btn.style.left = `${dx}px`
		this.draw(dx)
		this.emit(EN.onPick,dx*max/width)
	}
	onClick(e){
		e.stopPropagation()
		let target = e.target
		if(target!=this.cvs)return
		let rect = this.cvs.getBoundingClientRect()
		let dx = e.pageX-rect.left
		this.onEmit(dx)
	}
	initProgress(data){
		let {width,height} = this.rect
		this.cvs.merge({width,height})
		let {value,max} = data
		let ex = width*value/max
		this.draw(ex)
	}
	draw(ex){
		let ctx = this.ctx
		let {width,height} = this.rect
		ctx.fillStyle=UI.black
		ctx.clearRect(0,0,width,height)
		ctx.beginPath()
		ctx.fillRect(0,0,ex,height)
		ctx.closePath()
	}
	onFocusIn(data,wrap){
		/*
		{
			max,
			value
		}
		*/
		this.cacheData = data
		wrap.appendChild(this.$dom)
		let width = this.$dom.getBoundingClientRect().width-10
		this.rect = {width,height:5}
		this.initProgress(data)

		let tx = width * data.value/data.max
		this.btn.style.left=`${tx}px`
	}
}